import Hashes from "jshashes";
import fetch from "isomorphic-fetch";

let MD5 = new Hashes.MD5();
let DZAPP_KEY = "31d9770af28b3769";
let DZAPP_SECRET = "ba1b2922dda9f8ee";

let getSignStr = param => {
    let str = "";

    Object.keys(param)
        .sort()
        .map((name, index) => {
            // console.log(typeof(param[name]));
            if (typeof param[name] === "object") {
                str += name + getSignStr(param[name]);
            } else {
                str += name + param[name];
            }
        });
    return str;
};

const DevBaseUrl = "http://192.168.10.221:5080";
const ProdBashUrl = "https://weixin.hidizhu.com";

let restApiRequest = {
    getSign: request_param => {
        //  获取签名
        let timestamp = Date.parse(new Date()) / 1000; //精确到秒
        request_param = Object.assign(request_param, {
            appkey: DZAPP_KEY,
            timestamp: timestamp
        });

        //参数拼接后MD5
        let str = getSignStr(request_param);
        //console.log(str + DZAPP_SECRET);
        let sign = MD5.hex(str + DZAPP_SECRET);

        // 获取request_id
        let request_id = (Math.random() * 10).toString().replace(".", "");

        // 拼接post——data
        let dataArray = {
            sign: sign,
            param: request_param,
            request_id: request_id
        };
        let jsonData = JSON.stringify(dataArray, null, " ");
        return jsonData;
    },
    fetchp: (url, jsonData, method) => {
        let baseUrl = "";
        if (process.env.NODE_ENV === "production") {
            baseUrl = ProdBashUrl;
        } else {
            baseUrl = DevBaseUrl;
        }
        if (method == "get") {
            url = baseUrl + url + "?data=" + encodeURIComponent(jsonData);
            return fetch(url, {
                method: method,
                mode: "cors",
                headers: {
                    Accept: "application/json",
                    "Content-Type": "application/x-www-form-urlencoded"
                }
            });
        } else {
            url = baseUrl + url;
            return fetch(url, {
                method: "post",
                mode: "cors",
                headers: {
                    Accept: "application/json",
                    "Content-Type": "application/x-www-form-urlencoded"
                },
                body: "data=" + encodeURIComponent(jsonData)
            });
        }
    },
    fetchgetp: url => {
        return fetch(url, {
            method: "GET",
            mode: "cors",
            headers: {
                Accept: "text/html"
            }
        });
    }
};

let localStorage = {
    save: (key, value) => {
        localStorage
            .setItem(key, value)
            .then(() => console.log("cache ok->" + key))
            .catch(ex => {
                console.log("cache error->" + key);
                console.log(ex);
            });
    },
    load: key => {
        return localStorage.getItem(key);
    },
    init: () => {
        localStorage.setItem("aaa", "bbb").then(res => {
            console.log("save ok");
            AsyncStorage.getItem("bbb").then(res => {
                console.log("get ok");
                console.log(res);
            });
        });
    }
};

let formatDate = {
    format: time => {
        let da = new Date(parseInt(time) * 1000);
        let year = da.getFullYear() + "-";
        let month = da.getMonth() + 1 + "-";
        let date = da.getDate() + " ";
        return year + month + date + da.getHours() + ":" + da.getMinutes();
    }
};

export { localStorage, restApiRequest, formatDate };
